package blazingbubble.legacy.game.graphics;

import java.io.File;

import javax.media.opengl.GL;

import com.sun.opengl.util.texture.TextureCoords;
import spark.graphics.Texture;
import spark.graphics.Renderer;
import spark.exception.LoadingException;
import spark.math.Vector3;
import blazingbubble.legacy.game.BubbleField;
import blazingbubble.legacy.game.ChainReaction;
import blazingbubble.legacy.game.Bubble;

public class BubbleFieldRenderer
{
	private Texture background;
	private BubbleRenderer bubbleRenderer;

	public BubbleFieldRenderer()
	{
	}

	public void initializeWithTestLooks() throws LoadingException
	{
		background = Texture.newTexture(new File(BubbleRenderer.RESOURCES_PATH + "graphics/fb/test/bg.png"), true);
		bubbleRenderer = new BubbleRenderer();
		bubbleRenderer.initializeWithTestLooks();
	}

	public void render(BubbleField bubbleField, Vector3 leftBottom)
	{
		background.bind();
		TextureCoords coords = background.getImageTexCoords();

		Renderer.getInstance().getGl().glBegin(GL.GL_QUADS);

		Renderer.getInstance().getGl().glTexCoord2f(coords.left(), coords.bottom());
		Renderer.getInstance().getGl().glVertex3f(leftBottom.x, leftBottom.y, -10f);

		Renderer.getInstance().getGl().glTexCoord2f(coords.right(), coords.bottom());
		Renderer.getInstance().getGl().glVertex3f(leftBottom.x + bubbleField.getWidth(), leftBottom.y, -10f);

		Renderer.getInstance().getGl().glTexCoord2f(coords.right(), coords.top());
		Renderer.getInstance().getGl().glVertex3f(leftBottom.x + bubbleField.getWidth(), leftBottom.y + bubbleField.getHeight(), -10f);

		Renderer.getInstance().getGl().glTexCoord2f(coords.left(), coords.top());
		Renderer.getInstance().getGl().glVertex3f(leftBottom.x, leftBottom.y + bubbleField.getHeight(), -10f);

		Renderer.getInstance().getGl().glEnd();

		Renderer.getInstance().getGl().glBegin(GL.GL_LINES);

        for(ChainReaction c : bubbleField.activeChainReactions)
        {
            for(int v = 0; v < c.pointsx.length - 1; v++)
            {
                Renderer.getInstance().getGl().glVertex3f(c.pointsx[v].x, c.pointsx[v].y, -10f);
                Renderer.getInstance().getGl().glVertex3f(c.pointsx[v + 1].x, c.pointsx[v + 1].y, -10f);
            }
        }

		Renderer.getInstance().getGl().glEnd();

		Vector3 offset = new Vector3(leftBottom.x, leftBottom.y - 0.385f, leftBottom.z);
        for(Bubble aBubbleField : (Iterable<Bubble>) bubbleField)
        {
            bubbleRenderer.render(aBubbleField, offset);
        }
        for(Bubble debugBubble : bubbleField.debugBubbles)
        {
            bubbleRenderer.render(debugBubble, offset);
        }
	}
}
